﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace GameClient
{
    class SerializationClass 
    {
        /// <summary>
        /// 序列化编码
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static byte[] Serialization(object message)
        {
            if (message == null)
            { return null; }
            MemoryStream ms = new MemoryStream();
            BinaryFormatter mf = new BinaryFormatter();
            mf.Serialize(ms, message);//将message序列化后写入ms流中
            byte[] result = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, result.Length);
            ms.Close();
            return result;
        }
        /// <summary>
        /// 反序列化编码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static object DeSerialization(byte[] data)
        {
            if (data != null && data.Length > 0)
            {
                MemoryStream ms = new MemoryStream(data);
                BinaryFormatter bf = new BinaryFormatter();
                object result = bf.Deserialize(ms);//将ms流中的数据反序列化后赋给result
                ms.Close();
                return result;
            }
            else
                return null;
        }
    }
}
